package org.wattdepot.cli.commands;

import java.util.List;
import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.cli.UserCommandInterface;
import org.wattdepot.client.WattDepotClientException;
import org.wattdepot.resource.property.jaxb.Property;
import org.wattdepot.resource.sensordata.jaxb.SensorData;

/**
 * Lists the sensor data at given instance.
 * 
 * @author Jarret Mizo, Shaun Ramento
 * 
 */
public class ListSensorTimestamp extends UserCommandInterface implements UserCommands {

  @Override
  public String doCommand(String args) {
    String[] inputString = args.split(" ");
    String output = null;
    try {
      output = listSensorTimestamp(inputString[1], inputString[3]);
    }
    catch (WattDepotClientException e) {
      System.out.println("List summary error.");
    }
    return output;
  }

  /**
   * Prints information about a single sensor data instance.
   * 
   * @param sourceName Name of one of the public sources is the system.
   * @param timeStamp A date inputed with format YYYY-MM-DD.
   * @throws WattDepotClientException exception that is thrown
   * @return A string with sensor data instance information.
   */
  public String listSensorTimestamp(String sourceName, String timeStamp)
      throws WattDepotClientException {
    // holds the sensordata of sourceName
    SensorData sensordata;
    // holds the propertyList
    List<Property> propertyList;
    ValidateDay day = new ValidateDay();
    // gets the xml date of the string entered
    XMLGregorianCalendar xmlDate = day.validateDay(timeStamp);
    String newline = "\n";
    // holds the string that will be displayed
    StringBuffer buffer = new StringBuffer(100);

    // check if source with sourceName exists
    if (!sourceExists(sourceName)) {
      // exit method
      return "";
    }

    // checks if xmlDate was created if it is null, return to command prompt
    if (xmlDate == null) {
      return "";
    }

    // checks if source with XML date exists
    try {
      sensordata = getClient().getSensorData(sourceName, xmlDate);
    }
    catch (Exception exception) {
      // System.out.println("Source with date does not exist");
      return "Source with date does not exist";
    }

    // initializes sensordata with the sensordata information
    sensordata = getClient().getSensorData(sourceName, xmlDate);
    // gets the list of properties from the sensordata
    propertyList = sensordata.getProperties().getProperty();

    // append to the string that will be outputted
    buffer.append("Tool: " + sensordata.getTool() + "\nSource: " + sourceName + "\nProperties: ");

    for (Property property : propertyList) {
      buffer.append("(" + property.getKey() + " : " + property.getValue() + ")");
    }

    buffer.append(newline);
    return buffer.toString();

  }
}
